import re
import urllib
import os
import time
from Season import Season
from servicios.UrlHelper import UrlHelper
from LiLoader import LiLoader
from servicios.BeautifulSoup import BeautifulSoup
from servicios.Persistense import Persistense

class SeriesCache():
    _series = {}
    @staticmethod
    def get_instance(id):
        id = str(id)
        
        SeriesCache.load_instance(id)
        return SeriesCache._series[id][0]

    @staticmethod
    def load_instance(id):
        if not(SeriesCache._series.has_key(id)) or SeriesCache.check_expire(id):
            SeriesCache._series[id] = (Serie(id),time.time())

    @staticmethod
    def check_expire(id):
        timeout = Persistense.instance().get_expire_timeout()
        if SeriesCache._series[id][1] + timeout < time.time():
            return True
        return False

class Serie(LiLoader):
    @staticmethod
    def get_instance(idSerie):
        return SeriesCache.get_instance(idSerie)

    def get_season(self, nSeason):
        if (self._seasons is None):
            self.load_seasons()
        nSeason = str(nSeason)
        if (self.get_seasons().has_key(nSeason)):
            return self.get_seasons()[nSeason]
        return None

    def get_seasons(self):
        if (self._seasons is None):
            self.load_seasons()

        return self._seasons

    def load_seasons(self):
        html = UrlHelper.get_seasons(self._id)
        self._seasons = {}
        self.load_li(html)

    def load_especific_data(self, item):
        matches = re.findall('"(\d+)".*Temporada (\d+)', str(item)).pop(0)
        self._seasons[str(matches[1])] = Season(self,matches[0], matches[1])

    _id = 0
    _name = 0
    _img = ''
    _total_seasons = 0
    _seasons = None

    def __init__(self, idSerie):
        self._id = idSerie
        self.load_data()

    def get_id(self):
        return self._id

    def get_name(self):
        return self._name

    def get_img(self):
        return self._img

    def get_total_seasons(self):
        return self._total_seasons


    def load_data(self):
        html = UrlHelper.get_serie_data(self._id)
        soup = BeautifulSoup(html)

        item = soup.find("div", { "class" : "tit" })
        match = re.findall('>(.*)<', str(item))
        self._name = match[0]

        match = re.findall('<b>Temporadas:</b>[ ]*(\d+)', html)
        self._total_seasons = int(match[0])

        item = soup.find("img")
        match = re.findall('src="(.*)" border', str(item))
        self._img = match[0]

    def is_complete(self):
        p_serie = Persistense.instance().get_serie(self._id)
        last_season = self.get_season(p_serie['season'])
        last_chapter = last_season.get_chapter(p_serie['chapter'])
        return last_chapter.is_last()

    def get_image(self):
        file = Persistense.instance().get_app_path() + 'img/series/'+ str(self._id)+'.jpg'
        if not(os.path.exists(file)):
            image = urllib.URLopener()
            image.retrieve('http://www.cuevana.tv'+self._img, file)
        return file
        
